package org.jeecg.modules.demo.xxljob;/**
 * /**
 *
 * @Description:TODO
 * @author:yxx
 * @date:2022年10月2022/10/31日19:10
 */

import com.alibaba.fastjson.JSON;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
import org.apache.poi.hssf.usermodel.HSSFPatriarch;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.ClientAnchor;
import org.apache.poi.ss.usermodel.Workbook;
import org.jeecg.modules.demo.ch.Utils.DateUtil;
import org.jeecg.modules.demo.ch.common.CommonMst;
import org.jeecg.modules.demo.ch.entity.ChSoftwareOperationPlan;
import org.jeecg.modules.demo.ch.service.IChParameterService;
import org.jeecg.modules.demo.ch.service.IChSoftwareOperationPlanService;
import org.jeecg.modules.message.handle.impl.EmailSendMsgHandle;
import org.jeecgframework.poi.excel.ExcelExportUtil;
import org.jeecgframework.poi.excel.entity.TemplateExportParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * xxl-job定时任务测试
 */
@Component
@Slf4j
public class SoftwareExpirationJobHandler {

    @Autowired
    private IChParameterService iChParameterService;

    @Autowired
    private EmailSendMsgHandle emailSendMsgHandle;

    @Value("${jeecg.path.download}")
    private String download;

    @Value("${jeecg.path.template}")
    private String template;

    private Boolean isSendAttachment;//是否发送附件

    @Autowired
    private IChSoftwareOperationPlanService chSoftwareOperationPlanService;

    /**
     * 简单任务
     * 软硬件项目过期发送邮件
     *
     * @param params
     * @return
     */
    @XxlJob(value = "expirationSendEmail")
    public ReturnT<String> expirationSendEmail(String params) {

        //查询数据
        List<ChSoftwareOperationPlan> proData = getProData(chSoftwareOperationPlanService);
        //        String es_receiver="guyu@sz-changhong.com";
        String preMonth = DateUtil.getPreYearAndMonth(CommonMst.SOFTWARE.DATE_FORMAT2);//202212
        String es_title = preMonth + "授权情况";
        String es_content = "";
        if (CollectionUtils.isEmpty(proData)) {
            es_content = CommonMst.SOFTWARE.EMAIL_FORMAT2;
            isSendAttachment = false;//不发送附件
        } else {
            es_content = CommonMst.SOFTWARE.EMAIL_FORMAT;
            isSendAttachment = true; //发送邮件
            //导出excel
            exportExcel(es_title, proData);
        }
        //发送邮件
        //生成数据并发送邮箱
        String jobParam = XxlJobHelper.getJobParam();
        Map<String, Object> map = (Map<String, Object>) JSON.parse(jobParam);
        String emailReceivers = (String) map.get("emailReceiver");
        XxlJobHelper.log("jeecgBoot自定义的expirationSendEmail传入的emailReceivers{}", emailReceivers);

        if (emailReceivers.contains(",")) {
            String[] emailReceiver = emailReceivers.split(",");
            for (String emailAddress : emailReceiver) {
                emailSendMsgHandle.sendMsg(emailAddress, es_title, es_content, isSendAttachment);
            }
        } else {
            emailSendMsgHandle.sendMsg(emailReceivers, es_title, es_content, isSendAttachment);
        }
        return ReturnT.SUCCESS;
    }

    /**
     * 导出excel
     */
    public void exportExcel(String es_title, List<ChSoftwareOperationPlan> proData) {
        //1.构建需要导出的数据
        List<Map<String, Object>> listMap = new ArrayList<>();
        BigDecimal totalAmount = new BigDecimal(0);//总价
        for (ChSoftwareOperationPlan chSoftwareOperationPlan : proData) {
            Map<String, Object> lm = new HashMap<>();
            lm.put("itemName", chSoftwareOperationPlan.getItemName());
            lm.put("amount", chSoftwareOperationPlan.getAmount());
            if (null != chSoftwareOperationPlan.getAuthorizationDeadline()) {
                lm.put("authorizationDeadline", DateUtil.getFormateDateStr(chSoftwareOperationPlan.getAuthorizationDeadline(), CommonMst.SOFTWARE.DATE_FORMAT3));
            } else {
                lm.put("authorizationDeadline", "");
            }
            lm.put("hardwareAmount", chSoftwareOperationPlan.getHardwareAmount());
            if (null != chSoftwareOperationPlan.getHardWareAuthorizationDeadline()) {
                lm.put("hardWareAuthorizationDeadlineStr", DateUtil.getFormateDateStr(chSoftwareOperationPlan.getHardWareAuthorizationDeadline(), CommonMst.SOFTWARE.DATE_FORMAT3));
            } else {
                lm.put("hardWareAuthorizationDeadlineStr", "");
            }
            totalAmount = totalAmount.add(chSoftwareOperationPlan.getAmount()).add(chSoftwareOperationPlan.getHardwareAmount());
            listMap.add(lm);
        }
        //2.存放导出的数据
        Map<String, Object> map = new HashMap<>();
        map.put("title", es_title);
        map.put("totalAmount", totalAmount.doubleValue());
        TemplateExportParams params = getTemplateParams(CommonMst.SOFTWARE.TEMPLATE_NAME);
        map.put("maplist", listMap);
        Workbook workbook = ExcelExportUtil.exportExcel(params, map);

        File savefile = new File(download);
        if (!savefile.exists()) {
            savefile.mkdirs();
        }
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(download + es_title + ".xlsx");
            workbook.write(fos);
            fos.close();
        } catch (FileNotFoundException e) {
            log.error("exportExcel FileNotFoundException异常", e);
            e.printStackTrace();
        } catch (IOException e) {
            log.error("exportExcel IOException异常", e);
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    log.error("exportExcel IOException异常", e);
                    e.printStackTrace();
                }
            }
        }
    }


    //查询数据
    public static List<ChSoftwareOperationPlan> getProData(IChSoftwareOperationPlanService chSoftwareOperationPlanService) {
        String perFirstDayOfMonth = DateUtil.getPerFirstDayOfMonth(CommonMst.SOFTWARE.DATE_FORMAT);//下个月的第一天
        String nextMaxMonthDate = DateUtil.getNextMaxMonthDate(CommonMst.SOFTWARE.DATE_FORMAT);//下个月的最后一天
        Integer pageNo = 1;
        Integer pageSize = 1000;
        String authorizationDeadlineBegin = perFirstDayOfMonth;
        String authorizationDeadlineEnd = nextMaxMonthDate;
        String hardwareAuthorizationDeadlineBegin = perFirstDayOfMonth;
        String hardwareAuthorizationDeadlineEnd = nextMaxMonthDate;
        String hardExpirBeginTime = perFirstDayOfMonth;
        String hardExpirEndTime = nextMaxMonthDate;
        String softExpirBeginTime = perFirstDayOfMonth;
        String softExpirEndTime = nextMaxMonthDate;
        List<ChSoftwareOperationPlan> chSoftwareOperationPlanList = chSoftwareOperationPlanService.selectChSoftwareOperationPlanListByTime(pageNo, pageSize, authorizationDeadlineBegin, authorizationDeadlineEnd, hardwareAuthorizationDeadlineBegin, hardwareAuthorizationDeadlineEnd,hardExpirBeginTime,hardExpirEndTime,softExpirBeginTime,softExpirEndTime);
        return chSoftwareOperationPlanList;
    }

    /**
     * 返回导出参数对象
     *
     * @param name
     * @return
     */
    public TemplateExportParams getTemplateParams(String name) {
        return new TemplateExportParams(template + name);
    }

    public static Workbook exportProjectExcel() {
        TemplateExportParams params = new TemplateExportParams("D:\\opt\\template\\软件运维模板.xlsx");
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("title", "项目到期授权情况");
        map.put("totalAmount", "5000");
        map.put("srcPic", "D:\\opt\\upFiles\\temp\\02_1667184598543.jpg");
        List<Map<String, Object>> listMap = new ArrayList<Map<String, Object>>();
        for (int i = 0; i < 2; i++) {
            Map<String, Object> lm = new HashMap<String, Object>();
            lm.put("itemName", "项目" + i);
            lm.put("amount", "2" + i);
            lm.put("authorizationDeadline", "2022-11-01");
            lm.put("hardwareAmount", "2022-11-01");
            lm.put("hardWareAuthorizationDeadlineStr", "2022-11-02");
            listMap.add(lm);
        }

        map.put("maplist", listMap);
        Workbook workbook = ExcelExportUtil.exportExcel(params, map);

        return workbook;
    }

    public static void main(String[] args) throws IOException {
//        Workbook workbook = exportProjectExcel();
//        File savefile = new File("D:\\opt\\poi");
//        if (!savefile.exists()) {
//            savefile.mkdirs();
//        }
//        FileOutputStream fos = new FileOutputStream("D:\\opt\\poi\\result.xlsx");
//        workbook.write(fos);
//        fos.close();


//        //插入图片
//        Sheet sheet = workbook.getSheet("Sheet1");
//        Drawing<?> patriarch = sheet.createDrawingPatriarch();
////        HSSFPatriarch patriarch =  sheet.createDrawingPatriarch();
//        ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
////// 读取图片
////        File file = ResourceUtils.getFile("classpath:file/520.png");
////// 获取路径
////        String url = file.getAbsolutePath();
//        BufferedImage bufferImg = ImageIO.read(new File("D:\\opt\\upFiles\\temp\\02_1667184598543.jpg"));
//        ImageIO.write(bufferImg, "png", byteArrayOut);
//// 图片一导出到单元格A1中
//        HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 1023, 255, (short) 0, 0, (short) 0, 0);
//// 插入图片,注意这个问题PICTURE_TYPE_JPEG。如果导出的图片没有显示出来，改动这里
//        patriarch.createPicture(anchor, workbook.addPicture(byteArrayOut.toByteArray(), HSSFWorkbook.PICTURE_TYPE_JPEG));

        FileOutputStream fileOut = null;
        BufferedImage bufferImg = null;
        //先把读进来的图片放到一个ByteArrayOutputStream中，以便产生ByteArray
        try {
            ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
            bufferImg = ImageIO.read(new File("D:\\opt\\upFiles\\temp\\02_1667184598543.jpg"));
            ImageIO.write(bufferImg, "jpg", byteArrayOut);

            HSSFWorkbook wb = new HSSFWorkbook();
            HSSFSheet sheet1 = wb.createSheet("test picture");
            //画图的顶级管理器，一个sheet只能获取一个（一定要注意这点）
            HSSFPatriarch patriarch = sheet1.createDrawingPatriarch();
            //anchor主要用于设置图片的属性
            HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 1023, 255,(short)1, 8, (short) 2, 10);
            anchor.setAnchorType(ClientAnchor.AnchorType.DONT_MOVE_AND_RESIZE);
            //插入图片
            patriarch.createPicture(anchor, wb.addPicture(byteArrayOut.toByteArray(), HSSFWorkbook.PICTURE_TYPE_JPEG));
            fileOut = new FileOutputStream("D:\\opt\\poi\\result.xlsx");
            // 写入excel文件
            wb.write(fileOut);

            Workbook workbook = exportProjectExcel();
//            File savefile = new File("D:\\opt\\poi");
//            if (!savefile.exists()) {
//                savefile.mkdirs();
//            }
//            FileOutputStream fos = new FileOutputStream("D:\\opt\\poi\\result.xlsx");
            workbook.write(fileOut);
//            fos.close();

            System.out.println("----Excle文件已生成------");
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            if(fileOut != null){
                try {
                    fileOut.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

